<template>
  <div class="app-container">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        title="消耗登记"
        :btn-list="btnList"
        :needReturn="false"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-depotName>
                <el-input
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择仓库"
                  v-model="formInfo.data.depotName"
                >
                  <template #append>
                    <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-deptName>
                <el-input
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择出库部门"
                  v-model="formInfo.data.deptName"
                />
              </template>
              <template v-slot:form-consumeDeptName>
                <el-input
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择消耗部门"
                  v-model="formInfo.data.consumeDeptName"
                >
                  <template #append>
                    <el-icon @click="selectConsumeDept"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <div class="filter-wrapper">
              <page-filter :filter-list="filterInfo.list">
                <template v-slot:filter-addProduct>
                  <el-button :disabled="!canAddProduct" @click="addProduct"
                    >添加产品</el-button
                  >
                </template>
                <template v-slot:filter-removeProduct>
                  <el-button
                    :disabled="!canRemoveProduct"
                    @click="removeProduct()"
                    >删除产品</el-button
                  >
                </template>
                <template v-slot:filter-productCodeScan>
                  <ScanInputBox
                    :query="scanInfo.query"
                    :api="scanInfo.api"
                    :disabled="!canAddProduct"
                    @callback="onCallBackScanData"
                  />
                </template>
              </page-filter>
              <div class="display-flex">
                <el-button @click="preferenceInfo.visible = true"
                  >偏好设置</el-button
                >
              </div>
            </div>

            <div class="flex_full_item">
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summaryFieldList="tableInfo.summaryFieldList"
                  :tabIndex="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-qty="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <el-form-item
                        class="margin-bottom"
                        v-if="
                          scope.row.codeType === 1 || scope.row.codeType === 4
                        "
                      >
                        <div class="page-table-input-number-wrapper">
                          <div class="page-table-input-number-left">
                            <div class="page-table-input-number-item">
                              <el-form-item
                                :prop="`data.${scope.$index}.largeUnitQty`"
                                :rules="
                                  scope.$index >= 0
                                    ? [
                                        {
                                          validator: $validate.positiveAndZero,
                                          trigger: 'blur',
                                        },
                                      ]
                                    : []
                                "
                              >
                                <el-input-number
                                  style="width: 100%; margintop: 18px"
                                  v-model.lazy="scope.row.largeUnitQty"
                                  clearable
                                  controls-position="right"
                                  :precision="
                                    scope.row.qtyOperateMode === 0 ||
                                    scope.row.qtyOperateMode === 2
                                      ? 0
                                      : systemConfig.qty_show_precision
                                  "
                                  @change="
                                    changeLarge(
                                      $event,
                                      scope.row,
                                      `data.${scope.$index}.largeUnitQty`
                                    )
                                  "
                                  :min="0"
                                  :max="largeMax(scope.row)"
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.unitName }}
                              </div>
                            </div>
                            <div
                              class="page-table-input-number-item"
                              v-if="
                                scope.row.unitConvertCoefficient > 1 &&
                                scope.row.qtyOperateMode === 2
                              "
                            >
                              <el-form-item>
                                <el-input-number
                                  style="width: 100%; margintop: 18px"
                                  v-model.lazy="scope.row.smallUnitQty"
                                  clearable
                                  controls-position="right"
                                  :precision="0"
                                  :min="0"
                                  :max="smallMax(scope.row)"
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.calcUnitName }}
                              </div>
                            </div>
                          </div>
                          <div
                            class="page-table-input-number-right"
                            v-if="scope.row.qtyOperateMode === 2"
                          >
                            {{ $fn.qtyFormatter(scope.row.qty) }}
                          </div>
                        </div>
                      </el-form-item>
                      <span
                        v-else-if="
                          scope.row.codeType === 2 || scope.row.codeType === 3
                        "
                        >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                      >
                    </template>
                    <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:showDialog="selectDepotInfo.visible"
      :checkBox="false"
      :query="selectDepotInfo.query"
      :highlightRow="true"
      :checkLock="true"
      :saveEmpty="true"
      @callback="selectDepotCallBack"
    />

    <SelectDepotStorage
      v-if="selectDepotStorageInfo.visible"
      v-model:showDialog="selectDepotStorageInfo.visible"
      :query="selectDepotStorageInfo.query"
      :left-table-key="selectDepotStorageInfo.leftTableKey"
      :right-table-key="selectDepotStorageInfo.rightTableKey"
      :excludeQueryList="selectDepotStorageInfo.excludeQueryList"
      :showPrice="$permission('consume:price')"
      @callback="selectDepotStorageCallBack"
    />
    <!-- 选择部门 -->
    <select-dept
      v-if="deptInfo.visible"
      v-model:showDialog="deptInfo.visible"
      :query="deptInfo.query"
      @callback="selectDeptCallback"
      :checkBox="false"
      :highlightRow="true"
      :saveEmpty="true"
    />
    <select-individual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      v-model:leftQueryObj="individualInfo.leftQuery"
      v-model:rightQueryObj="individualInfo.rightQuery"
      v-model:infoList="individualInfo.productInfo"
      :requestRightList="!!orderId"
      :left-table-key="individualInfo.leftTableKey"
      v-model:rightApi="individualInfo.rightApi"
      v-model:leftApi="individualInfo.leftApi"
      v-model:rightVo="individualInfo.rightVo"
      :queryParams="individualInfo.queryParams"
      :showPrice="$permission('consume:price')"
      :scanInfo="scanInfo"
      @callbackSacn="callbackSacn"
      @callback="selectedProductDetails"
    />
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<script setup name="consume">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'
import PageFilter from '@/components/PageFilter/index'
import selectDepotStorage from '@/components/SelectDepotStorage/index'
import selectIndividual from '../components/individual'
import ScanInputBox from '../components/ScanInputBox'
import { getCoreSystemConfigAll } from '@/api/core'
import {
  batchValidateConsumeOrder,
  createConsumeOrder,
  updateConsumeOrder,
  detailConsumeOrder,
  getConsumeOrderDetailCustomizeListAll,
  depotStockCustomizeScanWithConsume,
  getDepotStockCustomizeListPage,
  depotStockValidateOptimalValidate,
} from '@/api/stock'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import SelectDept from '@/components/SelectDept/index'
import moment from 'moment'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/setPreferenceNoQuery')
)
const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: [String, Number],
  },
  orderId: {
    type: [String, Number],
  },
})

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const btnList = ref([{ label: '消耗', event: consume, show: true }])
const slipSelectRequest = ref(true)
const scanInfo = reactive({
  api: depotStockCustomizeScanWithConsume,
  query: {
    queryMap: {},
    customizeUserVO: {},
    queryParams: {
      depotId: proxy.$store.state.user.userInfo.coreResourcesVO
        ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
            '1'
          ) !== -1
          ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
          : ''
        : '',
      // validateExpire: false
    },
  },
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'productCodeScan' },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '个体操作',
        event: _selectIndividual,
        show: true,
        ifRender: ifRenderValue,
      },
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
//表单相关
const formInfo = reactive({
  ref: null,
  data: {
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
        : ''
      : '',
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
        : ''
      : '',
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    consumeDeptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    consumeDeptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
  },
  fieldList: [
    { label: '仓库', value: 'depotName', type: 'slot' },
    {
      label: '出库部门',
      value: 'deptName',
      type: 'input',
      placeholder: '出库部门',
      disabled: true,
    },
    {
      label: '消耗部门',
      value: 'consumeDeptName',
      type: 'slot',
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
  ],
  rules: {
    depotName: [{ required: true, message: '请选择仓库', trigger: 'change' }],
    consumeDeptName: [
      { required: true, message: '请选择消耗部门', trigger: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
  },
  labelWidth: '120px',
})
const selectDepotInfo = reactive({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 1,
    isCargoSpaceManage: 0,
  },
})
const selectDepotStorageInfo = reactive({
  leftTableKey:
    'productConsumePageWithDepotStockLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  rightTableKey:
    'productConsumePageWithDepotStockRight-com.slip.spd.entity.vo.stock.DepotStockVO',
  //库存产品
  visible: false,
  excludeQueryList: [], //库存产品左侧过滤配置
  query: {
    depotId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    generalProductCategory: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
    queryParams: {
      isEstimationStockBusiness: 1,
    },
  },
})
const individualInfo = reactive({
  visible: false,
  selectObj: {}, //库存产品弹窗左边后端合并项
  productInfo: {}, //个体操作的当前这条数据
  leftQuery: {}, //个体弹窗左边数据查询条件
  rightQuery: {}, //个体弹窗右边数据查询条件
  queryParams: {
    isEstimationStockBusiness: 1,
  },
  leftTableKey:
    'productConsumePageWithDepotStockRight-com.slip.spd.entity.vo.stock.DepotStockVO',
  rightApi: getConsumeOrderDetailCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getDepotStockCustomizeListPage, //个体弹窗左边数据接口
  rightVo: {}, //个体弹窗右边配置
})
const deptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const preferenceInfo = reactive({
  visible: false,
})

const formRefs = ref('')

watch(
  () => tableInfo.data,
  (val) => {
    if (val.length && !tableInfo.isSysGroup) {
      tableInfo.data.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        if (row.details && row.details.length) {
          row.details[0].qty = qty
          row.details[0].calcQty = calcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
  },
  {
    deep: true,
  }
)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.data.length
})
const canAddProduct = computed(() => {
  return formInfo.data.depotId && formInfo.data.deptId
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length
})

let obj = {
  qty: {
    label: '消耗数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('consume:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('consume:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('consume:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
getInvdividualRightCustomize()

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.fieldList, disStartDate, disEndDate)
setBusinessDate()
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  proxy.$nextTick(() => {
    if (!props.orderId) {
      formInfo.fieldList = formInfo.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function ifRenderValue() {
  return tableInfo.isSysGroup
}
async function callbackSacn(data, oldInfo, callback) {
  //个体操作弹窗扫码回调
  let { mergeDetail, detail } = data
  mergeDetail[0].details = [detail]

  let key = []
  tableInfo.sysGroup.forEach((row) => {
    let obj = {}
    obj.columnName = row.columnName
    obj.asTbName = row.asTbName
    obj.value = data[row.key] || null
    key.push(obj)
  })
  let newKey = JSON.stringify(key)
  if (tableInfo.map.has(newKey)) {
    if (
      oldInfo.groupConcatDepotStockIds.includes(detail.depotStockId.toString())
    ) {
      callback(true)
      return
    } else {
      if (oldInfo.key === newKey) {
        await setData(mergeDetail, newKey)
        await callback(false)
      } else {
        let value = tableInfo.map.get(newKey)
        if (
          await value.groupConcatDepotStockIds.includes(
            detail.depotStockId.toString()
          )
        ) {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          } else {
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          }
        } else {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(mergeDetail, newKey)
            await callback(false)
          } else {
            await setData(mergeDetail, newKey)
            await callback(false)
          }
        }
      }
    }
  } else {
    if ((await proxy.$fn.confirmRes()) === 'confirm') {
      await selectedProductDetails(oldInfo)
      await setData(mergeDetail, newKey)
      await callback(false)
    } else {
      await setData(mergeDetail, newKey)
      await callback(false)
    }
  }
}

async function setData(data, newKey, type = false) {
  //个体操作弹窗扫码回调设置数据

  let newData
  if (!type) {
    let map = await proxy.$fn.getDepotStorage(
      data,
      tableInfo.sysGroup,
      tableInfo.map,
      getConsumeOrderDetailCustomizeListAll,
      props.orderId,
      individualInfo.rightVo,
      'scan'
    )
    tableInfo.map = map
    tableInfo.data = [...map.values()]
    newData = map.get(newKey)
  } else {
    newData = tableInfo.map.get(newKey)
  }
  await getIndividualInfoQuery(newData)
}
async function onCallBackScanData(data, callback) {
  let { mergeDetail, detail } = data

  if (tableInfo.data && tableInfo.data.length) {
    let items = tableInfo.data.filter((row) => {
      if (detail.codeType === 2 || detail.codeType === 3) {
        let arr = proxy.$fn.splitArr(row.groupConcatDepotStockIds)
        let bool = arr.includes(detail.depotStockId.toString())
        return bool
      } else if (detail.codeType === 1 || detail.codeType === 4) {
        if (row.id === mergeDetail[0].id) {
          let num = proxy.$fn.Subtr(row.stockAvailableCalcQty, row.calcQty)
          if (num <= 1) {
            return row.calcQty === row.stockAvailableCalcQty
          }
        }
      }
    })
    if (items.length) {
      callback(true)
      return
    } else {
      callback(false)
    }
  }
  mergeDetail[0].details = [detail]
  let map = await proxy.$fn.getDepotStorage(
    mergeDetail,
    tableInfo.sysGroup,
    tableInfo.map,
    getConsumeOrderDetailCustomizeListAll,
    props.orderId,
    individualInfo.rightVo
  )
  tableInfo.map = map
  tableInfo.data = [...map.values()]
}
async function _selectIndividual(data) {
  //选择个体
  await getIndividualInfoQuery(data)
  individualInfo.visible = true
}
async function getIndividualInfoQuery(data) {
  // 设置个体操作参数
  for (let key in individualInfo.selectObj) {
    individualInfo.selectObj[key].value = data[key]
  }
  individualInfo.leftQuery.id = {
    queryType: 'NOT_IN',
    queryCategory: 'AND',
    value: data.groupConcatDepotStockIds,
  }
  individualInfo.leftQuery.productId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: data.productId,
  }
  individualInfo.leftQuery.depotId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: formInfo.data.depotId,
  }
  individualInfo.leftQuery = {
    ...individualInfo.leftQuery,
    ...individualInfo.selectObj,
  }
  individualInfo.rightQuery.id = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: data.groupConcatIds,
  }
  individualInfo.rightQuery.orderId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.orderId,
  }
  individualInfo.productInfo = data
}
async function selectedProductDetails(data) {
  //个体返回
  if (data.details && data.details.length) {
    tableInfo.map.set(data.key, data)
    let index = tableInfo.data.findIndex((item) => item.key === data.key)
    if (index !== -1) {
      tableInfo.data[index] = data
    }
  } else {
    removeProduct(data)
  }
}
function getMain() {
  detailConsumeOrder(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      scanInfo.query.queryParams.depotId = resp.data.depotId
    }
  })
  filterInfo.query.queryMap.orderId.value = props.orderId
  getList()
}
function getList() {
  //修改请求明细信息

  getConsumeOrderDetailCustomizeListAll(filterInfo.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let data = resp.data
      data.forEach((item) => {
        //将返回的数据变成Map形式
        let key = []
        tableInfo.sysGroup.forEach((row) => {
          let obj = {}
          obj.columnName = row.columnName
          obj.asTbName = row.asTbName
          obj.value = item[row.key]
          key.push(obj)
        })
        item.key = JSON.stringify(key)
        if (!tableInfo.isSysGroup) {
          item.groupConcatDepotStockIds = item.depotStockId.toString()
          item.groupSize = 1
          let row = proxy.$fn.deepClone(item)
          delete row.key
          item.details = [row]
        }
        tableInfo.map.set(item.key, item)
      })
      tableInfo.data = resp.data
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function consume() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const newDetails = tableInfo.data.filter((row) => row.productId)

    if (!newDetails.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }

    if (systemConfig.value.optimal_validate == 1) {
      let params = newDetails.map((item) => {
        return {
          calcQty: item.calcQty || '',
          depotStockId: item.depotStockId || '',
        }
      })
      depotStockValidateOptimalValidate(params).then((res) => {
        if (res && res.code && res.code == 200) {
          reSave(newDetails)
        }
      })
    } else {
      reSave(newDetails)
    }
  })
}
function reSave(newDetails) {
  let details = proxy.$fn.filterBlacklist(newDetails)
  //校验过期产品是否准许出库
  getCoreSystemConfigAll().then((resp) => {
    if (resp && resp.success) {
      let find = resp.data.find(
        (item) => item.systemConfigCode === 'allow_expire_out'
      )
      if (find) {
        let expire = validateExpire(newDetails)
        if (find.value === '1') {
          if (expire) {
            proxy
              .$confirm(expire + '是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                dangerouslyUseHTMLString: true,
              })
              .then(() => {
                const data = formInfo.data
                data.mergeDetails = details
                const validateApi = batchValidateConsumeOrder
                validateApi(data).then((resp) => {
                  if (resp && resp.success) {
                    const api = data.id
                      ? updateConsumeOrder
                      : createConsumeOrder
                    api(data).then((resp) => {
                      if (resp && resp.success) {
                        showDialog.value = false
                        emit('returnModify', false)
                        if (resp && resp.success) {
                          tableInfo.data = []
                          selectDepotStorageInfo.excludeQueryList = []
                          tableInfo.map = new Map()
                        }
                      }
                    })
                  }
                })
                return
              })
              .catch(() => {
                return
              })
          } else {
            const data = formInfo.data
            data.mergeDetails = details
            const validateApi = batchValidateConsumeOrder
            validateApi(data).then((resp) => {
              if (resp && resp.success) {
                const api = data.id ? updateConsumeOrder : createConsumeOrder
                api(data).then((resp) => {
                  if (resp && resp.success) {
                    showDialog.value = false
                    emit('returnModify', false)
                    if (resp && resp.success) {
                      tableInfo.data = []
                      selectDepotStorageInfo.excludeQueryList = []
                      tableInfo.map = new Map()
                    }
                  }
                })
              }
            })
          }
        } else {
          if (expire) {
            proxy.$alert(expire + '不允许出库！', '操作提示', {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true,
            })
            return
          } else {
            const data = formInfo.data
            data.mergeDetails = details
            const validateApi = batchValidateConsumeOrder
            validateApi(data).then((resp) => {
              if (resp && resp.success) {
                const api = data.id ? updateConsumeOrder : createConsumeOrder
                api(data).then((resp) => {
                  if (resp && resp.success) {
                    showDialog.value = false
                    emit('returnModify', false)
                    if (resp && resp.success) {
                      tableInfo.data = []
                      selectDepotStorageInfo.excludeQueryList = []
                      tableInfo.map = new Map()
                    }
                  }
                })
              }
            })
          }
        }
      } else {
        const data = formInfo.data
        data.mergeDetails = details
        const validateApi = batchValidateConsumeOrder
        validateApi(data).then((resp) => {
          if (resp && resp.success) {
            const api = data.id ? updateConsumeOrder : createConsumeOrder
            api(data).then((resp) => {
              if (resp && resp.success) {
                showDialog.value = false
                emit('returnModify', false)
                if (resp && resp.success) {
                  tableInfo.data = []
                  selectDepotStorageInfo.excludeQueryList = []
                  tableInfo.map = new Map()
                }
              }
            })
          }
        })
      }
    }
  })
}
function validateExpire(list = []) {
  let currentDate = moment().format('YYYY-MM-DD')
  let msg = ''
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}
//选择仓库
function selectStoreDepot() {
  selectDepotInfo.visible = true
}
function selectConsumeDept() {
  deptInfo.visible = true
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.data.consumeDeptName = row.name
    formInfo.data.consumeDeptId = row.id
  } else {
    formInfo.data.consumeDeptName = ''
    formInfo.data.consumeDeptId = ''
  }
}
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.data.depotId = data.id
    formInfo.data.depotName = data.name
    formInfo.data.deptName = data.deptName || ''
    formInfo.data.deptId = data.deptId || ''
    formInfo.data.consumeDeptName = data.deptName || ''
    formInfo.data.consumeDeptId = data.deptId || ''
    tableInfo.data = []
    tableInfo.map = new Map()
    scanInfo.query.queryParams.depotId = data.id
    selectDepotStorageInfo.excludeQueryList = []
  } else {
    formInfo.data.depotId = ''
    formInfo.data.depotName = ''
    formInfo.data.deptName = ''
    formInfo.data.deptId = ''
    formInfo.data.consumeDeptName = ''
    formInfo.data.consumeDeptId = ''
    tableInfo.data = []
    tableInfo.map = new Map()
    scanInfo.query.queryParams.depotId = ''
    selectDepotStorageInfo.excludeQueryList = []
  }
}
//选择库存产品
function addProduct() {
  let keys = [...tableInfo.map.keys()]
  let excludeQueryList = []
  if (keys.length && tableInfo.sysGroup.length) {
    excludeQueryList = keys.map((item) => JSON.parse(item))
  }
  selectDepotStorageInfo.excludeQueryList = excludeQueryList //库存产品左侧过滤配置
  selectDepotStorageInfo.query.depotId.value = formInfo.data.depotId
  selectDepotStorageInfo.visible = true
}
async function selectDepotStorageCallBack(rows = []) {
  //库存产品返回

  let map = await proxy.$fn.getDepotStorage(
    rows,
    tableInfo.sysGroup,
    tableInfo.map,
    getConsumeOrderDetailCustomizeListAll, //个体弹窗右边数据接口
    props.orderId,
    individualInfo.rightVo //个体弹窗右边表格配置
  )
  tableInfo.map = map
  tableInfo.data = [...map.values()]
}
//删除产品
function removeProduct(row = undefined) {
  if (row && row.key) {
    tableInfo.data = tableInfo.data.filter((item) => item.key !== row.key)
    let key = row.key
    tableInfo.map.delete(key)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.selections.forEach((row) => {
          for (let [key, value] of tableInfo.map) {
            if (key === row.key) {
              tableInfo.map.delete(key)
            }
          }
        })
        tableInfo.data = tableInfo.data.filter((row) => {
          return !tableInfo.selections.includes(row)
        })
      })
  }
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'consumeOrderDetailModify-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO',
  }
  tableInfo.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.isSysGroup = true
        }
      }
      slipSelectRequest.value = _slipSelectRequest
      filterInfo.query.customizeUserVO = data
      getDeoptLeftCustomize()
    }
  })
}
function getDeoptLeftCustomize() {
  //库存产品弹窗左侧配置

  let param = {
    tableKey:
      'productConsumePageWithDepotStockLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      let obj = {}
      if (tableInfo.isSysGroup) {
        for (let key in data.detail) {
          if (data.detail[key].sysGroupLevel > 0) {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
            obj[key] = {
              queryType: 'EQUALS',
              queryCategory: 'AND',
              ignoreEmptyValue: false,
              value: null,
            }
          }
        }
      } else {
        arr.push({
          columnName: data.detail.id.columnName,
          asTbName: data.detail.id.asTbName,
          key: 'depotStockId',
        })
        obj['depotStockId'] = {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: null,
        }
      }
      individualInfo.selectObj = obj
      tableInfo.sysGroup = arr
      scanInfo.query.customizeUserVO = data
      if (props.orderId) {
        getMain()
      }
    }
  })
}
function getInvdividualRightCustomize() {
  //获取个体弹窗右边配置
  let param = {
    tableKey:
      'stockConsumeModifySingle-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      individualInfo.rightVo = res.data
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.page-table > .el-table) {
  overflow: hidden;
}
</style>
